package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-pro/cache"
	"recruit-pro/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Rec{}).Count(&count)

	var rec []models.Rec
	redis_key := "rec_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&rec).Debug()
		jsonData, _ := json.Marshal(rec)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &rec)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"rec":   rec,
		},
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var rec models.Rec
	redis_key := "rec_id" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&rec).Debug()
		jsonData, _ := json.Marshal(rec)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &rec)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": rec,
	})
	return

}

func Coll(c *gin.Context) {
	id := c.Query("id")
	var rec models.Rec
	redis_key := "rec_id" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&rec).Debug()
		jsonData, _ := json.Marshal(rec)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &rec)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": rec,
	})
	return
}
